<?php
	include_once("Database.inc");
	
class Department {
	
	public $id;
	public $description;
	
	public static function getAllDepartments() {
		$d = array();
		
		$query = $GLOBALS["DB"] -> doQuery("SELECT DEPARTMENTCODE, DEPARTMENTDESC FROM DEPARTMENTS ORDER BY DEPARTMENTCODE");
		
		while ($row = mssql_fetch_array($query)) {
			array_push($d, Department::getDepartmentFromArray($row));
		}
		
		return $d;
	}
	
	public static function getDepartment($id) {
		$query = $GLOBALS["DB"] -> 
			doQuery("SELECT DEPARTMENTCODE, DEPARTMENTDESC FROM DEPARTMENTS WHERE DEPARTMENTCODE=$id");
			
		if ($row = mssql_fetch_array($query)) {
			return Department::getDepartmentFromArray($row);
		} else {
			return null;
		}
	}
	
	protected static function getDepartmentFromArray($array) {
		$d = new Department();
		
		$d->id = $array[0];
		$d->description = $array[1];
		
		return $d;
	}
	
	/*
	 * Updates the specified department in the database.  If the oldCode is empty, then
	 * the department is added.  Otherwise, an existing record is modified.
	 */
	 public static function updateDepartment($department, $oldCode) {	 
	 	$query = "";
	 	if ($oldCode == "0") {
	 		$query = 
	 			"INSERT INTO DEPARTMENTS(DEPARTMENTCODE, DEPARTMENTDESC) VALUES ('$department->id', '$department->description');";
	 	} else {
	 		$query = 
	 			"UPDATE DEPARTMENTS SET DEPARTMENTCODE='$department->id', DEPARTMENTDESC='$department->description' WHERE DEPARTMENTCODE=$oldCode;";
	 	}
	 	
	 	$GLOBALS["DB"] -> doQuery($query);
	 }
}

?>